/**
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。
 * 版权所有：忠旺机械设备制造有限公司
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。
 * 软件版本：Ver 1.0.0
 * 文件路径：com.zhongwang.mms.module.purchase.controller
 * 创建时间：2020年04月11日 16时42分
 **/
package com.zhongwang.mms.module.purchase.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhongwang.mms.annotation.RepeatCommit;
import com.zhongwang.mms.base.BaseController;
import com.zhongwang.mms.common.ImportCallBack;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.PChangeOrder;
import com.zhongwang.mms.gen.entity.TWarehouseInfo;
import com.zhongwang.mms.module.basic.service.TWarehouseInfoService;
import com.zhongwang.mms.module.buy.listner.ImportShoppingPlanRowNoListener;
import com.zhongwang.mms.module.buy.model.ImportShoppingPlanRowNoModel;
import com.zhongwang.mms.module.purchase.excelListener.PChangeOrderListener;
import com.zhongwang.mms.module.purchase.model.*;
import com.zhongwang.mms.module.purchase.service.PurChangeService;
import com.zhongwang.mms.module.purchase.service.PurWarehouseInfoService;
import com.zhongwang.mms.util.DateUtil;
import com.zhongwang.mms.util.FileUtils;
import com.zhongwang.mms.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName： PurChangeController
 * @Description： 串料控制层
 * @Author： 徐一贺
 * @Date： 2020/4/11 16:42
 * @Version： V1.0
 **/
@Controller
@RequestMapping("/purchase/change")
public class PurChangeController extends BaseController {
    @Autowired
    private PurChangeService purChangeService;



    @GetMapping("/index")
    /**
     *@FunctionName: index
     *@Description: 跳转到串料申请列表页面
     *@Author: 徐一贺
     *@CreateDate: 2020/4/18 11:20
     *@Phone: 18241927380
     *@Return: java.lang.String 页面路径
     *@Version: 1.0.0
     */
    public String index(Model model) {
        List<TWarehouseInfo> warehouseInfoList = purChangeService.findWarehouseInfoList();
        String whiIds = "";
        for (TWarehouseInfo tWarehouseInfo:warehouseInfoList) {
            whiIds+=tWarehouseInfo.getWhiId()+",";
        }
        whiIds=whiIds.substring(0,whiIds.length()-1);
        model.addAttribute("warehouseInfoList", warehouseInfoList);
        model.addAttribute("whiIds", whiIds);
        return "/purchase/purInvManage/change/page";
    }

    /**
     * @FunctionName: createPage
     * @Description: 跳转到申请串料申请页面
     * @Author: 徐一贺
     * @CreateDate: 2020/4/18 11:20
     * @Phone: 18241927380
     * @Return: java.lang.String 页面路径
     * @Version: 1.0.0
     */
    @GetMapping("/createPage")
    public String createPage(Model model) {
        //防重复提交
        String uuid = UUID.randomUUID().toString();
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute(uuid,uuid);
        model.addAttribute("fromId", uuid);

        model.addAttribute("mode", "create");
        model.addAttribute("ceoId", 0);
        model.addAttribute("ceoAppPerson", ShiroUtils.getUser().getName());
        model.addAttribute("ceoAppPersonId", ShiroUtils.getUser().getId());
        model.addAttribute("ceoAppDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString());
        return "/purchase/purInvManage/change/create/page";
    }

    /**
     * @FunctionName: createPage
     * @Description: 跳转到编辑查看串料申请页面
     * @Author: 徐一贺
     * @CreateDate: 2020/4/18 11:20
     * @Phone: 18241927380
     * @Return: java.lang.String 页面路径
     * @Version: 1.0.0
     */
    @GetMapping("/createPage/{mode}/{ceoId}")
    public String createPage(Model model, @PathVariable("mode") String mode, @PathVariable("ceoId") String ceoId) {
        ChangeModel changeModel = purChangeService.getChangeModel(ceoId);
        model.addAttribute("mode", mode);
        model.addAttribute("ceoId", changeModel.getCeoId());
        model.addAttribute("ceoAppPerson", changeModel.getCeoAppPerson());
        model.addAttribute("ceoAppPersonId", changeModel.getCeoAppPersonId());
        model.addAttribute("ceoAppDate", new SimpleDateFormat("yyyy-MM-dd").format(changeModel.getCeoAppDate()).toString());
        return "/purchase/purInvManage/change/create/page";
    }


    /**
     * @FunctionName: execPage
     * @Description: 跳转到串料申请执行页面
     * @Author: 徐一贺
     * @CreateDate: 2020/4/21 19:37
     * @Phone: 18241927380
     * @Return: java.lang.String 页面路径
     * @Version: 1.0.0
     */
    @GetMapping("/execPage")
    public String execPage(Model model) {
        List<TWarehouseInfo> warehouseInfoList = purChangeService.findWarehouseInfoList();
        String whiIds = "";
        for (TWarehouseInfo tWarehouseInfo:warehouseInfoList) {
            whiIds+=tWarehouseInfo.getWhiId()+",";
        }
        whiIds=whiIds.substring(0,whiIds.length()-1);
        model.addAttribute("warehouseInfoList", warehouseInfoList);
        model.addAttribute("whiIds", whiIds);
        return "/purchase/purInvManage/change/exec/page";
    }
    /**
     * @FunctionName: execPage
     * @Description: 跳转到串料申请执行页面
     * @Author: 徐一贺
     * @CreateDate: 2020/4/21 19:37
     * @Phone: 18241927380
     * @Return: java.lang.String 页面路径
     * @Version: 1.0.0
     */
    @GetMapping("/execPage/{totalPrice}/{year}/{month}")
    public String execPage(Model model,@PathVariable("totalPrice") String totalPrice,@PathVariable("year") Integer year,@PathVariable("month") Integer month) {

        model.addAttribute("mode","index_exec");
        model.addAttribute("totalPrice",totalPrice);
        String start = DateUtil.getFirstDayOfMonth(month);
        start = start.replace(start.substring(0,start.indexOf("-")),year.toString());
        model.addAttribute("start",start.substring(0,10));
        String end = DateUtil.getLastDayOfMonth(month);
        end = end.replace(end.substring(0,end.indexOf("-")),year.toString());
        model.addAttribute("end",end.substring(0,10));

        List<TWarehouseInfo> warehouseInfoList = purChangeService.findWarehouseInfoList();
        String whiIds = "";
        for (TWarehouseInfo tWarehouseInfo:warehouseInfoList) {
            whiIds+=tWarehouseInfo.getWhiId()+",";
        }
        whiIds=whiIds.substring(0,whiIds.length()-1);
        model.addAttribute("warehouseInfoList", warehouseInfoList);
        model.addAttribute("whiIds", whiIds);
        return "/purchase/purInvManage/change/exec/page";
    }


    @GetMapping("/exportPage")
    /**
     *@FunctionName: exportPage
     *@Description: 跳转到导出模板页面
     *@DesignIdea: 请填写导出模页面支持导出搜索结果
     *@Author: 徐一贺
     *@CreateDate: 2020/6/15 8:04
     *@Phone: 18241927380
     *@Param: [mode]
     *@Return: java.lang.String
     *@Version: v 1.0.0
     */
    public String exportPage(Model mode) {
        mode.addAttribute("mode", "change");
        return "/purchase/purInvManage/change/export/page";
    }

    @GetMapping("/importPage")
    /**
     *@FunctionName: importPage
     *@Description: 跳转到批量标记导入页面
     *@DesignIdea: 跳转到批量标记导入页面
     *@Author: 徐一贺
     *@CreateDate: 2020/6/15 13:31
     *@Phone: 18241927380
     *@Param: [mode]
     *@Return: java.lang.String
     *@Throw:
     *@Version: v 1.0.0
     */
    public String importPage(Model mode) {
        mode.addAttribute("userId", ShiroUtils.getUserId());
        return "/purchase/purInvManage/change/import/page";
    }

    @PostMapping("/findProCodeList")
    @ResponseBody
    /**
     *@FunctionName: findProCodeList
     *@Description: 根据项目号模糊查询获取看板系统项目信息与本地系统项目状态列表
     *@Author: 徐一贺
     *@CreateDate: 2020/4/18 12:50
     *@Phone: 18241927380
     *@Param: [param] 参数
     *@Return: com.zhongwang.mms.common.JsonResult 返回查询结果
     *@Version: 1.0.0
     */
    public JsonResult findProCodeList(VWProject param) {
        List<VWProject> vwProjectList = purChangeService.findVWProjectByLikeCode(param);
        return JsonResult.success("", vwProjectList);
    }

    @PostMapping("/list")
    @ResponseBody
    @RequiresPermissions({"purinv:purchalist:view"})
    /**
     *@FunctionName: list
     *@Description: 获取串料申请列表
     *@Author: 徐一贺
     *@CreateDate: 2020/4/15 19:39
     *@Phone: 18241927380
     *@Param: [queryModel] 检索参数
     *@Return: [List<ChangeModel>] 串料申请列表
     *@Version: 1.0.0
     */
    public JsonResult list(ChangeOrderQueryModel queryModel) {
        startPage();
        return jsonResult(purChangeService.findChangeOrderListByQuery(queryModel));
    }

    @PostMapping("/execList")
    @ResponseBody
    @RequiresPermissions({"purinv:purexeccha:view"})
    /**
     *@FunctionName: execList
     *@Description: 获取串料执行列表
     *@Author: 徐一贺
     *@CreateDate: 2020/4/15 19:39
     *@Phone: 18241927380
     *@Param: [queryModel] 检索参数
     *@Return: [List<ChangeModel>] 串料执行列表
     *@Version: 1.0.0
     */
    public JsonResult execList(ChangeOrderQueryModel queryModel) {
        startPage();
        return jsonResult(purChangeService.findChangeOrderExecListByQuery(queryModel));
    }


    @PostMapping("/deptList")
    @ResponseBody
    /**
     *@FunctionName: deptList
     *@Description: 获取单位列表
     *@Author: 徐一贺
     *@CreateDate: 2020/4/21 10:12
     *@Phone: 18241927380
     *@Param: []
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult deptList() {
        return JsonResult.success("", purChangeService.findDeptList());
    }


    @PostMapping("/codeExist")
    @ResponseBody
    /**
     *@FunctionName: codeExist
     *@Description: bootstrapValidate验证：验证项目号是否存在
     *@JavaScriptDemo： notEmpty: {message: '请输入需求项目编号'},
     *                         threshold: 6, //有6字符以上才发送ajax请求，（input中输入一个字符，插件会向服务器发送一次，设置限制，6字符以上才开始）
     *                         remote: {//ajax验证。server result:{"valid",true or false} 向服务发送当前input name值，获得一个json数据。例表示正确：{"valid",true}
     *                             url: 'purchase/change/codeExist',//验证地址
     *                             message: '用户已存在',//提示消息
     *                             delay: 100,//每输入一个字符，就发ajax请求，服务器压力还是太大，设置2秒发送一次ajax（默认输入一个字符，提交一次，服务器压力太大）
     *                             type: 'POST'//请求方式
     *                             /**自定义提交数据，默认值提交当前input value
     *                              *  data: function(validator) {
     *                                return {
     *                                    password: $('[name="passwordNameAttributeInYourForm"]').val(),
     *                                    whatever: $('[name="whateverNameAttributeInYourForm"]').val()
     *                                };
     *                             }
     *
     *
     *@Author: 徐一贺
     *@CreateDate: 2020/4/18 13:24
     *@Phone: 18241927380
     *@Param: [param] 项目号
     *@Return: java.lang.Boolean
     *@Version: 1.0.0
     */
    public String codeExist(VWProject param) {
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", purChangeService.codeExist(param));
        String resultString = "";
        ObjectMapper mapper = new ObjectMapper();
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }


    @PostMapping("proInfoExist")
    @ResponseBody
    /**
     *@FunctionName: 根据项目号查询本系统项目是否存在
     *@Description: 请填写方法描述
     *@Author: 徐一贺
     *@CreateDate: 2020/4/20 13:31
     *@Phone: 18241927380
     *@Param: [param] 项目号
     *@Return: [String] 返回结果
     *@Version: 1.0.0
     */
    public String proInfoExist(VWProject param) {
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", purChangeService.proInfoExist(param));
        String resultString = "";
        ObjectMapper mapper = new ObjectMapper();
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }


    @PostMapping("/getPInventory")
    @ResponseBody
    /**
     *@FunctionName: getPInventory
     *@Description: 根据需求的库存信息主键查找库存信息并且转换成串料需要的信息
     *@Author: 徐一贺
     *@CreateDate: 2020/4/18 10:09
     *@Phone: 18241927380
     *@Param: [ceoUseItyId] 需求的库存信息主键
     *@Return: [pInventory] 查找到了库存信息
     *@Version: 1.0.0
     */
    public JsonResult getPInventory(ChangeModel param) {
        PChangeOrder pChangeOrder = purChangeService.getPInventory(param.getCeoUseItyId());

        return JsonResult.success("加载成功！", pChangeOrder);
    }


    @PostMapping("/toChange")
    @ResponseBody
    @RequiresPermissions({"purinv:purchalist:edit"})
    /**
     *@FunctionName: toChange
     *@Description: 生成串料单
     *@Author: 徐一贺
     *@CreateDate: 2020/4/16 10:54
     *@Phone: 18241927380
     *@Param: [param] 前台参数
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult toChange(ChangeModel param) {
        if (purChangeService.toChange(param)) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    @PostMapping("/save")
    @ResponseBody
    @RequiresPermissions({"purinv:purchalist:edit"})
    @RepeatCommit
    /**
     *@FunctionName: save
     *@Description: 保存串料标记
     *@Author: 徐一贺
     *@CreateDate: 2020/4/20 11:17
     *@Phone: 18241927380
     *@Param: [param]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult save(PChangeOrder param) {
        return purChangeService.saveChangeOrder(param);
    }

    @PostMapping("/submitAppy")
    @ResponseBody
    @RequiresPermissions({"purinv:purchalist:edit"})
    /**
     *@FunctionName: submitAppy
     *@Description: 提交
     *@Author: 徐一贺
     *@CreateDate: 2020/4/21 12:39
     *@Phone: 18241927380
     *@Param: [param]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult submitAppy(PChangeOrderModel param) {
        if (purChangeService.submitAppy(param)) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    @PostMapping("/execApply")
    @ResponseBody
    @RequiresPermissions({"purinv:purexeccha:edit"})
    /**
     *@FunctionName: execAppy
     *@Description: 执行
     *@Author: 徐一贺
     *@CreateDate: 2020/4/21 12:39
     *@Phone: 18241927380
     *@Param: [param]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult execApply(PChangeOrderModel param) {
        JsonResult jsonResult = new JsonResult();
        String msg = purChangeService.execApply(param);
        if (!msg.contains("执行失败")) {
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
        }
        jsonResult.setMsg(msg);
        return jsonResult;
    }

    @PostMapping("/removeApply")
    @ResponseBody
    @RequiresPermissions({"purinv:purchalist:edit"})
    /**
     *@FunctionName: removeApply
     *@Description: 删除作废
     *@Author: 徐一贺
     *@CreateDate: 2020/4/21 12:39
     *@Phone: 18241927380
     *@Param: [param]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult removeApply(PChangeOrderModel param) {
        if (purChangeService.removeApply(param)) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    @PostMapping("/reject")
    @ResponseBody
    @RequiresPermissions({"purinv:purexeccha:edit"})
    /**
     *@FunctionName: reject
     *@Description: 驳回
     *@Author: 徐一贺
     *@CreateDate: 2020/4/21 12:39
     *@Phone: 18241927380
     *@Param: [param]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult reject(PChangeOrderModel param) {
        return purChangeService.reject(param);
    }

    @PostMapping("/revokeAppy")
    @ResponseBody
    @RequiresPermissions({"purinv:purexeccha:edit"})
    /**
     *@FunctionName: revokeAppy
     *@Description: 撤销
     *@Author: 徐一贺
     *@CreateDate: 2020/4/22 9:16
     *@Phone: 18241927380
     *@Param: [param]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult revokeAppy(PChangeOrderModel param) {
        if (purChangeService.revokeAppy(param)) {
            return JsonResult.success();
        }
        return JsonResult.fail("因串料需求的串料库存信息因被标记或库存不足导致无法撤销！");
    }


    @PostMapping("/inventoryList")
    @ResponseBody
    /**
     *@FunctionName: inventoryList
     *@Description: 获取项目在库库存列表
     *@Author: 徐一贺
     *@CreateDate: 2020/4/23 9:15
     *@Phone: 18241927380
     *@Param: [param] 查询参数
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 1.0.0
     */
    public JsonResult inventoryList(PInventoryModel param) {
        startPage();
        List<PInventoryModel> inventoryList = purChangeService.findInventoryList(param);
        return jsonResult(inventoryList);
    }

    @PostMapping("/getChangeOrder")
    @ResponseBody
    /**
     *@FunctionName: getChangeOrder
     *@Description: 根据主键获取串料信息
     *@Author: 徐一贺
     *@CreateDate: 2020/4/24 14:32
     *@Phone: 18241927380
     *@Param: [param]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version: 2.0.0
     */
    public JsonResult getChangeOrder(PChangeOrderModel param) {
        return JsonResult.success("", purChangeService.getChangeModel(param.getCeoIds()));
    }

    @PostMapping("/exportPurInvExcel")
    @ResponseBody
    /**
     *@FunctionName: exportPurInvExcel
     *@Description: 导出执行列表
     *@DesignIdea:
     *@Author: 徐一贺
     *@CreateDate: 2020/6/13 15:49
     *@Phone: 18241927380
     *@Param: [response, param]
     *@Return: void
     *@Throw:
     *@Version: v1.0.0
     */
    public JsonResult exportPurInvExcel( PurInvQueryModel param) {
        return purChangeService.exportPurInvExcel(param);
    }


    @GetMapping("/errorExport/{userId}")
    @ResponseBody
    /**
     *@FunctionName: errorExport
     *@Description: 导出15天内错误串料信息
     *@DesignIdea:
     *@Author: 徐一贺
     *@CreateDate: 2020/6/13 15:49
     *@Phone: 18241927380
     *@Param: [response, param]
     *@Return: void
     *@Throw:
     *@Version: v1.0.0
     */
    public void errorExport(HttpServletResponse response, @PathVariable("userId") Integer userId) {
        purChangeService.errorExport(response, userId);
    }

    @PostMapping("/importExcel")
    @ResponseBody
    /**
     *@FunctionName: importExcel
     *@Description: 导入批量串料标识Excel
     *@DesignIdea: 请填写设计思想
     *@Author: 徐一贺
     *@CreateDate: 2020/6/15 14:49
     *@Phone: 18241927380
     *@Param: [file]
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Throw:
     *@Version: v 1.0.0
     */
    public JsonResult importExcel(MultipartFile file) {
        return purChangeService.importExcel(file);
    }
}